Page({
  data: {
    userInfo: null,
    hasUserInfo: false,
  },

  onLoad: function () {
    // 检查用户是否已经登录
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true,
      });
      this.redirectToRolePage(userInfo.role);
    }
  },

  getUserProfile: function () {
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途
      success: (res) => {
        const userInfo = res.userInfo;
        // 假设这里调用后端接口获取用户角色
        this.login(userInfo);
      },
      fail: (err) => {
        console.log('获取用户信息失败', err);
      },
    });
  },

  login: function (userInfo) {
    wx.login({
      success: (res) => {
        if (res.code) {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          wx.request({
            url: 'https://your-backend-url.com/login',
            method: 'POST',
            data: {
              code: res.code,
              userInfo: userInfo,
            },
            success: (res) => {
              const { openId, role } = res.data;
              userInfo.openId = openId;
              userInfo.role = role;
              wx.setStorageSync('userInfo', userInfo);
              this.setData({
                userInfo: userInfo,
                hasUserInfo: true,
              });
              this.redirectToRolePage(role);
            },
            fail: (err) => {
              console.log('登录失败', err);
            },
          });
        } else {
          console.log('登录失败！' + res.errMsg);
        }
      },
    });
  },

  redirectToRolePage: function (role) {
    if (role === 'member') {
      wx.redirectTo({
        url: '/pages/userInfo/userInfo',
      });
    } else if (role === 'admin') {
      wx.redirectTo({
        url: '/pages/admin/admin',
      });
    }
  },
});